
package com.zcp.pcsuitall;

import com.zcp.pcsuitall.business.AppInfoObject;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.StatFs;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class SuitUtil {

    /**
     * 获取IP地址。
     * 
     * @return
     */
    public static String getLocalIpAddress() {
//        return "127.0.0.1";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                    .hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                        .hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("222", ex.toString());
        }
        return null;
    }

    public static boolean isWifiEnable(Context context) {
        boolean success = false;
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (wifiManager.isWifiEnabled()) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo != null) {
                    // Log.i("222", "wifi"+wifiInfo.getIpAddress());
                    success = (wifiInfo.getIpAddress() > 0);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success;
    }

    public static int getWifiState(Context context) {
        int status = WifiManager.WIFI_STATE_UNKNOWN;
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            status = wifiManager.getWifiState();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return status;
    }

    /**
     * 获取第三方安装的应用程序APK名称列表。
     * 
     * @return
     */
    public static LinkedList<String> getDataApp(Context context) {

        LinkedList<String> apksource = new LinkedList<String>();
        List<ApplicationInfo> packs = context.getPackageManager().getInstalledApplications(
                PackageManager.GET_UNINSTALLED_PACKAGES);
        if (packs != null) {
            for (ApplicationInfo appInfo : packs) {
                boolean flag = false;
                if ((appInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                    // Updated system app
                    flag = true;
                } else if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                    // Non-system app
                    flag = true;
                }
                if (flag) {
                    apksource.add(appInfo.sourceDir);
                }
            }
        }

        return apksource;

    }

    /**
     * 获取图片信息。
     * 
     * @return String[] 是二维数组，第一维是图片名称，第二维是图片保存路径,第三维是ID。
     */
    public static Cursor getImageInfo(Context context,Uri url) {

        Cursor cursor = MediaStore.Images.Media.query(context.getContentResolver(), url,
                new String[] {
                        MediaStore.Images.ImageColumns.DISPLAY_NAME,
                        MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns._ID,
                        MediaStore.Images.ImageColumns.DATE_ADDED,MediaStore.Images.ImageColumns.DATE_TAKEN

                // 就是路径 注意 DATE_ADDED单位是 seconds DATE_TAKEN是拍摄时间单位是毫秒
                });
        return cursor;

    }

    /**
     * 获取缩略图片信息。
     * 
     * @return String[] 是二维数组，第一维是图片ID，第二维是图片保存路径。
     */
    public static HashMap<String, String> getThumbnailsImageInfo(Context context,Uri url) {
        HashMap<String, String> thumbnailsImageInfoMap = new HashMap<String, String>();
        Cursor cursor = null;
        try {

            cursor = MediaStore.Images.Thumbnails.query(context.getContentResolver(), url,
                    new String[] {
                            MediaStore.Images.Thumbnails.IMAGE_ID,
                            MediaStore.Images.Thumbnails.DATA
                    // 就是路径
                    });
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    thumbnailsImageInfoMap.put(cursor.getInt(0) + "", cursor.getString(1));

                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return thumbnailsImageInfoMap;

    }
    
    /**
     * 获取缩略图片信息。
     * 
     * @return String
     */
    public static String getThumbnailsImageInfoByImageId(Context context,Uri url,String imageId) {
        if(imageId==null)
        {
            return null;
        }
        String value=null;
        Cursor cursor = null;
        try {

            cursor = MediaStore.Images.Thumbnails.query(context.getContentResolver(), url,
                    new String[] {
                            MediaStore.Images.Thumbnails.IMAGE_ID,
                            MediaStore.Images.Thumbnails.DATA
                    // 就是路径
                    });
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    if(imageId.equals(cursor.getInt(0) + ""))
                    {
                        value=cursor.getString(1);
                        break;
                    }                   

                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return value;

    }    

    /**
     * 判断是否是系统软件。
     * 
     * @param flag
     * @return
     */
    public static boolean isSystemApp(int flag) {
        if ((flag & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
            return false;
        } else if ((flag & ApplicationInfo.FLAG_SYSTEM) == 0) {
            return false;
        }
        return true;
    }
    
    /**
     * 判断是否安装在sdcard中。
     * 
     * @param flag
     * @return
     */
    public static boolean isInstallSdcard(AppInfoObject element) {
        boolean result = false;
        try {
            if (android.os.Build.VERSION.SDK_INT < 8) {
                result = element.getSourcePath().startsWith("/sdcard");

            } else {
                result = ((element.getFlag() & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    } 

    /**
     * 获取应用程序数量。包括系统程序。
     * 
     * @param context
     * @return count[0]为系统程序数量 ,count[1]为用户安装程序数量
     */
    public static int[] getAppNumber(Context context) {
        int[] counts = new int[2];
        int sys_count = 0;
        int user_count = 0;
        PackageManager mPm = context.getPackageManager();

        List<ApplicationInfo> installedAppList = mPm
                .getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        // count=installedAppList.size();
        for (ApplicationInfo appInfo : installedAppList) {
            if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
                sys_count++;
            } else {
                user_count++;
            }

        }
        counts[0] = sys_count;
        counts[1] = user_count;
        return counts;
    }

    /**
     * 获取多媒体-图片的数量,图片总大小。
     * 
     * @return 返回多媒体的数量。
     */
    public static long[] getImageNumber(Context context, Uri url) {

        long count = 0;
        long size = 0;
        Cursor cursor = null;
        try {
            cursor = MediaStore.Images.Media.query(context.getContentResolver(), url, new String[] {
                    MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.SIZE
            });
            if (cursor != null && cursor.moveToFirst()) {
                String path = null;
                do {
                    path = cursor.getString(0);
                    // 去掉应用程序中的图片
                    if (path == null) {
                        continue;
                    }
                    // 去掉应用程序中图片
                    if (path.contains("drawable") && path.endsWith("png")) {
                        continue;
                    }
                    count++;
                    size = size + cursor.getLong(1);

                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        Log.i("222", url + "count=" + count + "||size=" + size);
        return new long[] {
                count, size
        };

    }

    /**
     * 获取视频的数量,和总大小。
     * 
     * @return 返回视频的数量。
     */
    public static long[] getVideoNumber(Context context, Uri url) {

        long count = 0;
        long size = 0;
        Cursor cursor = null;
        try {
            cursor = MediaStore.Video.query(context.getContentResolver(), url, new String[] {
                    MediaStore.Video.VideoColumns.DISPLAY_NAME, MediaStore.Video.VideoColumns.DATA,
                    MediaStore.Video.VideoColumns.SIZE
            });

            if (cursor != null && cursor.moveToFirst()) {
                count = cursor.getCount();
                // Log.i("222", url+"number is "+count);
                do {
                    // Log.i("222",
                    // cursor.getString(0)+"||"+cursor.getString(1));
                    size = size + cursor.getLong(2);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        // Log.i("222", url+"count="+count+"||size="+size);
        return new long[] {
                count, size
        };

    }

    /**
     * 获取音频的数量。
     * 
     * @return 返回音频的数量。
     */
    public static long[] getAudioNumber(Context context, Uri url) {
        // Log.i("222", "getAudioNumber");
        long count = 0;
        long size = 0;
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(
                    url,
                    new String[] {
                            MediaStore.Audio.AudioColumns.IS_MUSIC,
                            MediaStore.Audio.AudioColumns.DISPLAY_NAME,
                            MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.SIZE
                    }, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                // Log.i("222", url+"number is "+count);
                do {
                    // Log.i("222",
                    // cursor.getInt(0)+"||"+cursor.getString(1)+"||"+cursor.getString(2));
                    if (cursor.getInt(0) > 0) {
                        count++;
                        size = size + cursor.getLong(3);
                    }
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        // Log.i("222", url+"count="+count+"||size="+size);
        return new long[] {
                count, size
        };

    }

    /**
     * 处理获取短信总条数方法。
     */
    public static int getAllSmsCount(Context context) {
        Cursor c = null;
        int sms_count = 0;
        Uri uri = Uri.parse("content://sms");
        c = context.getContentResolver().query(uri, new String[] {
            "count(*) as sms_count"
        }, null, null, null);
        if (c != null && c.moveToFirst()) {
            sms_count = c.getInt(0);
        }
        c.close();
        // Log.i("222", "sms_count is="+sms_count);
        return sms_count;
    }

    /**
     * 获取所有联系人数量。
     * 
     * @param context
     * @return
     */
    public static int getAllContactCount(Context context) {
        int count = 0;
        Cursor c = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
                null, RawContacts.DELETED + "<>1", null, null);
        if (c != null && c.moveToFirst()) {
            count = c.getCount();
        }
        c.close();
        // Log.i("222", "ContactCount is="+count);
        return count;
    }

    /**
     * 获取SD卡信息,返回的值空闲大小和总大小。
     * 
     * @param context
     * @return
     */
    public static long[] getSdAvailableSpace() {
        // linux把设备当作文件处理,从系统中获取SD设备
        File path = Environment.getExternalStorageDirectory();
        // 新建一个stat，它可以查看路径上面的系统文件
        StatFs stat = new StatFs(path.getPath());
        // 一个块的 有多少字节
        long blockSize = stat.getBlockSize();
        // 设备上有多少个空闲的块
        long availableBlock = stat.getAvailableBlocks();
        // 设备上所有的块
        long totalBlocks = stat.getBlockCount();
        // 换算成字节
        long availablePlace = availableBlock * blockSize;

        long totalPlace = totalBlocks * blockSize;

        return new long[] {
                availablePlace, totalPlace
        };
    }

    /**
     * 获取SD卡信息,返回的值空闲大小和总大小。
     * 
     * @param context
     * @return
     */
    public static long[] getSystemAvailableSpace() {
        // linux把设备当作文件处理,从系统中获取SD设备
        File path = Environment.getDataDirectory();
        // 新建一个stat，它可以查看路径上面的系统文件
        StatFs stat = new StatFs(path.getPath());
        // 一个块的 有多少字节
        long blockSize = stat.getBlockSize();
        // 设备上有多少个空闲的块
        long availableBlock = stat.getAvailableBlocks();
        // 设备上所有的块
        long totalBlocks = stat.getBlockCount();
        // 换算成字节
        long availablePlace = availableBlock * blockSize;

        long totalPlace = totalBlocks * blockSize;

        return new long[] {
                availablePlace, totalPlace
        };
    }

    public static void openWifiSetting(Activity context, int requestCode) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.android.settings",
                "com.android.settings.wifi.WifiSettings"));
        context.startActivityForResult(intent, requestCode);
    }

    public static void openHotSetting(Activity context, int requestCode) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.android.settings",
                "com.android.settings.wifi.WifiApSettings"));
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 获取更携式WLAN热点。
     * 
     * @param context
     * @return
     */
    public static boolean getWifiApEnable(Activity context) {
        boolean isEnable = false;
        WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        try {
            Method method2 = mWifiManager.getClass().getMethod("isWifiApEnabled");
            isEnable = (Boolean) method2.invoke(mWifiManager);
        } catch (Exception e) {
        }
        Log.e("222", "getWifiApEnable " + isEnable);
        return isEnable;
    }

    /**
     * 判断sdcard是否可用。
     * 
     * @return
     */
    public static boolean isSdcardCanUser() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取IP地址对应转换的编码。
     * 
     * @param ip
     * @return
     */
    public static String getVerificationCode(String ip) {
        String result = "";
        try {
            String[] ips = ip.split("\\.");
            // Log.i("222", ip);
            int value = 0;
            String temp = "";
            for (String element : ips) {
                value = Integer.valueOf(element);
                temp = Integer.toHexString(value);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                // Log.i("222", element+"||"+temp+"||"+temp.length());
                result = result + temp;
                temp = null;

            }
            // Log.i("222", result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    // /**
    // * 从编码中获取ip。
    // * @param ipCode
    // * @return
    // */
    // public static String getIpByVerificationCode(String ipCode) {
    // String result = "";
    // try {
    // String[] ips = ip.split(".");
    // int value = 0;
    // for (String element : ips) {
    // Log.i("222", element);
    // value = Integer.valueOf(element);
    // result=result+Integer.toHexString(value);
    // Log.i("222", Integer.toHexString(value));
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // return result;
    //
    // }

    /**
     * 获取音乐信息
     * 
     * @param context
     * @param columns
     * @param where
     * @return
     */
    public static Cursor getMusicInfo(Context context, String[] columns, String where) {
        return query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, where, null,
                null, 0);
    }

    public static Cursor query(Context context, Uri uri, String[] projection, String where,
            String[] selectionArgs, String sortOrder, int limit) {
        try {
            ContentResolver resolver = context.getContentResolver();
            if (resolver == null) {
                return null;
            }
            if (limit > 0) {
                uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
            }
            return resolver.query(uri, projection, where, selectionArgs, sortOrder);
        } catch (UnsupportedOperationException ex) {
            return null;
        }
    }

    /**
     * 发送一个连接状态广播。
     * 
     * @param isConnection
     */
    public static void sendConnectionStatusMes(Context context, boolean isConnection) {
        if (context != null) {
            Intent intent = new Intent(PhoneServiceAllActivity.CONNECTION_STATUS);
            intent.putExtra(PhoneServiceAllActivity.CONNECTION_STATUS_KEY, isConnection);
            context.sendBroadcast(intent);
        }
    }

    /**
     * 通知系统扫描文件，path只能是文件路径，不能是文件夹。 系统会自动根据path是存放到哪里自动扫描到 内库或者外裤中。
     * 根据path是否已Environment
     * .getExternalStorageDirectory().getPath()（/mnt/sdcard）开头。
     * 
     * @param context
     * @param path
     * @since 1.0版本
     */
    public static void scanFile(Context context, String path) {
        scanFile(context, new String[] {
            path
        }, null, new MyOnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Log.i("222", "Scanned " + path + ":");
                Log.i("222", "-> uri=" + uri);
            }
        });

    }

    public static void scanFile(Context context, String[] paths, String[] mimeTypes,
            MyOnScanCompletedListener callback) {
        MyClientProxy client = new MyClientProxy(paths, mimeTypes, callback);
        MediaScannerConnection connection = new MediaScannerConnection(context, client);
        client.mConnection = connection;
        connection.connect();
    }

    static class MyClientProxy implements MediaScannerConnectionClient {
        final String[] mPaths;

        final String[] mMimeTypes;

        final MyOnScanCompletedListener mClient;

        MediaScannerConnection mConnection;

        int mNextPath;

        MyClientProxy(String[] paths, String[] mimeTypes, MyOnScanCompletedListener client) {
            mPaths = paths;
            mMimeTypes = mimeTypes;
            mClient = client;
        }

        public void onMediaScannerConnected() {
            scanNextPath();
        }

        public void onScanCompleted(String path, Uri uri) {
            if (mClient != null) {
                mClient.onScanCompleted(path, uri);
            }
            scanNextPath();
        }

        void scanNextPath() {
            if (mNextPath >= mPaths.length) {
                mConnection.disconnect();
                return;
            }
            String mimeType = mMimeTypes != null ? mMimeTypes[mNextPath] : null;
            mConnection.scanFile(mPaths[mNextPath], mimeType);
            mNextPath++;
        }
    }

    /**
     * Interface for notifying clients of the result of scanning a requested
     * media file.
     */
    public interface MyOnScanCompletedListener {
        /**
         * Called to notify the client when the media scanner has finished
         * scanning a file.
         * 
         * @param path the path to the file that has been scanned.
         * @param uri the Uri for the file if the scanning operation succeeded
         *            and the file was added to the media database, or null if
         *            scanning failed.
         */
        public void onScanCompleted(String path, Uri uri);
    }

}
